<template>
    <el-dialog v-model="dialogVisible" :title="titleText" width="450" :close-on-click-modal="false"
        @close="handleClose">
        <el-form :model="form" :rules="rules" label-width="auto" label-position="right" ref="formRef" label-suffix=":">
            <el-form-item label="角色名称" required prop="name">
                <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, reactive, watch } from 'vue';
import { getRole, createRole, updateRole } from '@/common/apis/projectMember/index.ts';
import { useRoute } from 'vue-router';

interface Props {
    modeType: string; // edit | add
    modelValue: boolean;
    id: number;
}

const props = defineProps<Props>();
const route = useRoute();
const formRef = ref(null);
const form = ref({
    name: '',
    description: ''
});

const emit = defineEmits(['update:modelValue', 'changed']);

const rules = reactive({
    name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 15, message: '角色名称长度在 2 到 15 个字符', trigger: 'blur' }
    ],
});

const dialogVisible = computed(() => {
    return props.modelValue;
});

const titleText = computed(() => {
    return props.modeType === 'add' ? '添加角色' : '编辑角色';
});

const getDetail = async () => {
    if (props.modeType === 'edit' && props.id) {
        const { data } = await getRole({ projectId: Number(route.params.id), roleId: props.id }) as any;
        form.value = data;
    }
};

watch(() => dialogVisible.value,
    val => {
        if (dialogVisible.value && props.modeType === 'edit') {
            getDetail();
        }
    }
);

// 关闭时重置表单
const handleClose = () => {
    form.value = { name: '', description: '' };
    formRef.value?.resetFields();
    emit('update:modelValue', false);
};

const handleSubmit = async () => {
    if (!formRef.value) return;
    try {
        await formRef.value.validate();
        const _params = { projectId: Number(route.params.id), ...form.value, roleId: props.modeType === 'add' ? null : props.id };
        const _method = props.modeType === 'add' ? createRole : updateRole;
        const res = await _method(_params) as any;
        ElMessage.success({ message: `${res.message}` });
        emit('changed');
        handleClose();
    } catch (error) {
    }
};
</script>